package com.innovation.wjrpc.rpc;

import com.innovation.wjrpc.codec.Decoder;
import com.innovation.wjrpc.codec.Encoder;
import com.innovation.wjrpc.communication.NettyTransportClient;
import com.innovation.wjrpc.loader.TransportSelector;
import com.innovation.wjrpc.protocol.Request;
import com.innovation.wjrpc.protocol.Response;
import com.innovation.wjrpc.result.AsyncResponse;
import com.innovation.wjrpc.result.ResultsMap;
import com.innovation.wjrpc.status.AsyncResponseStatus;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @author innoyiya
 * @date 2021/9/9 15:58
 */
public class NettyRemoteInvoker extends RemoteInvoker {


    public NettyRemoteInvoker(Class clazz, Encoder encoder, Decoder decoder, TransportSelector selector) {
        super(clazz, encoder, decoder, selector);
    }

    @Override
    Response invokeRemote(Request request) {
        NettyTransportClient client = null;
        try {
            client = (NettyTransportClient) selector.select();
            ByteBuf byteBuf = Unpooled.buffer();
            byteBuf.writeBytes(encoder.encode(request));
            ResultsMap.setResponseById(request.getId());
            client.write(byteBuf);
            //todo 发送请求后的处理

            return ResultsMap.getResponseById(request.getId());

        }finally {
            if (client != null) selector.release(client);
        }
    }
}
